package com.neu.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.neu.R;

public class LoginActivity extends AppCompatActivity {
    private EditText et_username;
    private EditText et_password;
    private CheckBox cb_saveorno;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //获得
        et_username=findViewById(R.id.et_username);
        et_password=findViewById(R.id.et_password);
        cb_saveorno=findViewById(R.id.cb_saveorno);

        readConfigAndUpadteUI();

    }

    private void readConfigAndUpadteUI() {
        //读取xml
        SharedPreferences sp=getSharedPreferences("config",Context.MODE_PRIVATE);
        String readuser=sp.getString("username","");
        String readpass=sp.getString("password","");
        //将信息放入到文件框中
        et_username.setText(readuser);
        et_password.setText(readpass);

        if(!TextUtils.isEmpty(readpass)&&!TextUtils.isEmpty(readuser)){
            cb_saveorno.setChecked(true);
        }else{
            cb_saveorno.setChecked(false);
        }

    }

    public void loginClicked(View view) {
        String username=et_username.getText().toString().trim();
        String password=et_password.getText().toString().trim();
        Log.d("TAG", username+"-----"+password);
        if(TextUtils.isEmpty(username) || TextUtils.isEmpty(password)){
            Toast.makeText(this,"用户名密码不能空",Toast.LENGTH_LONG).show();
            return ;//防止程序向下执行
        }
        //张三和123456
        if(username.equals("zhangsan") && password.equals("123456")){
            Toast.makeText(this,"登录成功",Toast.LENGTH_LONG).show();
            //登录成功密码保存
            if(cb_saveorno.isChecked()){//用户选中
                saveUsernameAndPassword(username,password);
            }

        }else{
            Toast.makeText(this,"登录失败",Toast.LENGTH_LONG).show();
        }
    }

    private void saveUsernameAndPassword(String username, String password) {
        SharedPreferences sp=getSharedPreferences("config", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();
        editor.putString("username",username);
        editor.putString("password",password);
        editor.commit();

    }
}